
/****************************************************************************/
/*Copyright (c) 2011, Florent DEVILLE.                                      */
/*All rights reserved.                                                      */
/*                                                                          */
/*Redistribution and use in source and binary forms, with or without        */
/*modification, are permitted provided that the following conditions        */
/*are met:                                                                  */
/*                                                                          */
/* - Redistributions of source code must retain the above copyright         */
/*notice, this list of conditions and the following disclaimer.             */
/* - Redistributions in binary form must reproduce the above                */
/*copyright notice, this list of conditions and the following               */
/*disclaimer in the documentation and/or other materials provided           */
/*with the distribution.                                                    */
/* - The names of its contributors cannot be used to endorse or promote     */
/*products derived from this software without specific prior written        */
/*permission.                                                               */
/* - The source code cannot be used for commercial purposes without         */ 
/*its contributors' permission.                                             */
/*                                                                          */
/*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         */
/*LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         */
/*FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            */
/*COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       */
/*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,      */
/*BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;          */
/*LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER          */
/*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT        */
/*LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN         */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/*POSSIBILITY OF SUCH DAMAGE.                                               */
/****************************************************************************/

#pragma once

#include "RTToolTypes.h"
#include "RTRay.h"

#include "RTMatrix44.h"

//constante for coordinate system
#define RIGHT_HANDED 1
#define LEFT_HANDED 0

namespace RT
{
	//forward declaration
	class RTIPrimitive;

	/*Raytracer singleton class creating a picture*/
	class RTRaytracer
	{
	public:
		/*Levels of oversampling*/
		enum OVERSAMPLING
		{
			NO_OVERSAMPLING = 1,
			LVL1_OVERSAMPLING = 2,
			LVL2_OVERSAMPLING = 4
		};

	private:

		//singleton variable
		static RTRaytracer* m_instance;

		//camera location
		RTPoint3f m_origin;

		//camera direction
		RTVector3f m_direction;

		//view matrix
		RTMatrix44 m_viewMatrix;

		//screen width in pixels
		I32 m_pixelWidth;

		//screen height in pixels
		I32 m_pixelHeight;

		//screen width in space
		F32 m_width;

		//screen height in space
		F32 m_height;

		//camera field of view
		F32 m_fov;

		//precomputed pixel width
		F32 m_precompWidth;

		//precomputed pixel height
		F32 m_precompHeight;

		//precomputed pixel offset in x coordinate
		F32 m_precompPixelOffsetX;

		//precomputed pixel offset in y coordinate
		F32 m_precompPixelOffsetY;

		//Level of oversampling used
		OVERSAMPLING m_overSamplingLevel;

		//flag for color swapped. If true, colors are GBR, if false : RGB.
		bool _colorSwapped;

		//flag to true when the rendering loop gotta stop
		bool _stopRendering;

		//flag for right handed coordinate system. If true, +x = right, +y = up, +z=toward. False : +z=backward
		bool _handedness;

	private:
		//generate the primary ray for a specific pixel
		void generateRay(I32 x, I32 y, RTRay& ray)const;

		//generate oversampling rays
		void generateOverSamplingRay(I32 x, I32 y, RTRay* ray)const;

		/*Compute the color of a ray*/
		void computeColor(const RTRay& ray, RTColor& color, I32 reflection, F32 refractionIndex)const;

		/*Update the precomputed variables*/
		void updateParameters();

		/*Return the refraction vector*/
		RTVector3f getRefractionVector(const RTVector3f& normal, const RTVector3f& incident, const RTVector3f& hit, 
			F64 n1, F64 n2)const;

		/* Return the normalized reflection vector of the incident vector*/
		RTVector3f getReflectionVector(const RTVector3f& normal, const RTVector3f& incident)const;

		/*Calcualte the refletance when going through an object*/
		F32 reflectance(const RTVector3f& normal, const RTVector3f& incident, F64 n1, F64 n2)const;

		/*Default Constructor*/
		RTRaytracer();

		/*Constructor*/
		RTRaytracer(I32 pixelWidth, I32 pixelHeight, F32 width, F32 height, F32 fov);

		/*Destructor*/
		~RTRaytracer();

		//Pipeline rendering function returning the intersected primitive.
		inline void PIPELINEgetPrimitive(const RTRay& primaryRay, F32& dist, RTPoint3f& center, RTIPrimitive** RTPrimitive);

		//Pipeline rendering function returning the raw pixel color.
		inline void PIPELINEgetRawColor(const RTIPrimitive& primitive, const RTVector3f& center, RTColor& output);

		//Pipeline rendering function calculating the normal
		inline void PIPELINEgetNormal(const RTIPrimitive& primitive, const RTRay& primaryRay, const RTPoint3f& center, const F32& dist, RTVector3f& output);

		//Pipeline rendering function calculating the color of a pixel using light
		inline void PIPELINEcomputeLight(const RTVector3f& direction, const RTPoint3f& center, const RTVector3f& normal, const RTIPrimitive& primitive,
			const RTColor& I32put, RTColor& output);

		//Pipeline rendering function calculating the transparancy color
		inline void PIPELINEcomputeTransparency(const RTRay& incidentRay, F32 dist,
		const RTNormal3f& normal, F32 incidentRefraction, F32 reflectedRefraction,
		const RTColor& inputColor, RTColor& outputColor);

	public:
		//singleton gettors
		static RTRaytracer& getInstance();

		/*Destroy the singleton*/
		void close();

		//prepare the raytracer for rendering
		void preDraw();

		//Render the scene
		void draw(char* screenBuffer, I32 reflection)const;

		/*Set camera position, direction and up vector*/
		void setViewer(const RTVector3f& eye, const RTVector3f& at, const RTVector3f& up);

		/*Set picture resolution*/
		void setResolution(I32 pixelWidth, I32 pixelHeight);

		/*Set screen ratio and field of view*/
		void setScreen(F32 ratioWidth, F32 ratioHeight, F32 fov);

		/*Set oversampling level used to render the scene*/
		void setOverSampling(OVERSAMPLING lvl_ovs);

		/*Get the pixel width of the picture*/
		I32 getPixelWidth()const;

		/*Get the pixel height of the picture*/
		I32 getPixelHeight()const;

		/*Get the scene's view matrix*/
		RTMatrix44 getViewMatrix()const;

		//set the color swapped flag. If true, color order is BGR. If false : RGB
		void setColorSwapped(bool colorSwapped);

		//set the stop signal for the rendering loop
		void setStopSignal(bool stop);

		//set the coordinate system (use LEFT_HANDED or RIGHT_HANDED). Has to be set before the viewer.
		void setCoordinateSystem(bool handedness);

	};

	#define RAYTRACER RTRaytracer::getInstance()
}